package com.github.pig.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.common.util.TreeUtil;
import com.github.pig.admin.mapper.SysLabelMapper;
import com.github.pig.admin.model.dto.LabelTree;
import com.github.pig.admin.model.entity.SysLabel;
import com.github.pig.admin.service.SysLabelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysLabelServiceImpl extends ServiceImpl<SysLabelMapper,SysLabel> implements SysLabelService {

    @Autowired
    private SysLabelMapper mapper;

    @Override
    public List<Integer> getPathById(Integer id) {
        String paths = mapper.getPathById(id);
        List<Integer> pathList = new ArrayList<>();
        String[] pathArry = paths.split(",");
        for (String path: pathArry) {
            if (path.equals("0")){
                continue;
            }
            pathList.add(Integer.parseInt(path));
        }
        pathList.add(id);
        return pathList;
    }

    @Override
    public List<LabelTree> selectListTree(EntityWrapper<SysLabel> labelEntityWrapper) {
        return getChannelSourceTree(this.selectList(labelEntityWrapper), 0);
    }


    /**
     * 构建部门树
     *
     * @param ChannelSources 渠道来源
     * @param root  根节点
     * @return
     */
    private List<LabelTree> getChannelSourceTree(List<SysLabel> ChannelSources, int root) {
        List<LabelTree> trees = new ArrayList<>();
        LabelTree node;
        for (SysLabel source : ChannelSources) {
            if (source.getParentId().equals(source.getId())) {
                continue;
            }
            node = new LabelTree();
            node.setId(source.getId());
            node.setParentId(source.getParentId());
            node.setLabel(source.getName());
            node.setValue(source.getId());
            trees.add(node);
        }
        return TreeUtil.bulidByUser(trees, root);
    }




}
